Skip to content

Escape TAB/LF/CR again when serializing to XML - #1093

Open
Lyin-OTTF wants to merge 1 commit into
stleary:masterfrom
Lyin-OTTF:fix/xml-serialize-escape-whitespace
Open

Lyin-OTTF wants to merge 1 commit into
stleary:masterfrom
Lyin-OTTF:fix/xml-serialize-escape-whitespace

Conversation

@Lyin-OTTF

Copy link
Copy Markdown

Description

Fixes #1092.

XML.mustEscape() is shared by two callers that need opposite answers for TAB (0x9), LF (0xA) and CR (0xD):

  • XML.escape() uses it to decide what to escape when serializing.
  • XMLTokener.unescapeEntity() uses it to reject invalid numeric character references when parsing.

#1070 added those three codepoints to the valid-range clause so that unescape("
") works again (#1059). A side effect was that the serialization path stopped escaping literal TAB/LF/CR: XML.toString() and JSONML.toString() now write them as literal characters. Conforming XML parsers normalize whitespace, so a value like "Lettuce\nTomato" loses its line breaks when the generated XML is read back by any standard parser — the attribute value comes back as "Lettuce Tomato" (or with collapsed whitespace), and XML.toJSONObject(XML.toString(o)) does not return the original string.

This PR splits the two concerns:

Tests

Three new tests in XMLTest:

  • testEscapesLiteralWhitespaceControlCharsOnSerialization — XML.toString() writes 
/	/
 for literal TAB/LF/CR. Fails on master.
  • testWhitespaceControlCharsRoundTripThroughXml — XML.toJSONObject(XML.toString(o)) returns the original value with the line break intact.
  • testJSONMLToStringEscapesLiteralNewlines — same requirement for JSONML.toString().
mvn test
Tests run: 827, Failures: 0, Errors: 0, Skipped: 6

The existing #1059/#1070 regression tests (testValidWhitespaceNumericEntityUnescape, testValidWhitespaceNumericEntityToJSONObject) still pass.

@stleary

stleary commented Oct 20, 2026

Copy link
Copy Markdown
Owner

@Lyin-OTTF No files changed?

@Lyin-OTTF
Lyin-OTTF force-pushed the fix/xml-serialize-escape-whitespace branch from 1cf10b5 to 3b93afd Compare October 21, 2026 01:23
@Lyin-OTTF

Copy link
Copy Markdown
Author

The first push came out empty. I built the tree with the Git Data API and reused the parent tree, so the changed files never made it into the commit - the tree was identical to master, which is what you saw.

Force-pushed the same commit with the actual changes. The diff is there now: 3 files, +80/-20.

src/main/java/org/json/XML.java           | 44 ++++++++-------
src/main/java/org/json/XMLTokener.java    |  6 +++-
src/test/java/org/json/junit/XMLTest.java | 50 +++++++++++++++

Tests: 827 run, 0 failures, 0 errors, 6 skipped. The three new tests in XMLTest fail without the main-source change and pass with it.

@stleary

stleary commented Oct 25, 2026

Copy link
Copy Markdown
Owner

@Lyin-OTTF Looks like you have an undocumented behavior change. For example, the following test case fails with a parsing JSONException in the master branch, but executes successfully in your branch.

    @Test
    public void foo() {
        String xmlStr =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
                        "<name>Joe &#133; Tester</name>\n";
        JSONObject jsonObject = XML.toJSONObject(xmlStr);
        String expectedStr = "{\"name\":\"Joe \u0085 Tester\"}";
        JSONObject expectedJsonObject = new JSONObject(expectedStr);
        Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
    }

@Lyin-OTTF

Copy link
Copy Markdown
Author

@stleary Thanks for flagging this — you're right, and it is an intentional (if under-documented) consequence of the fix. Let me explain the root cause.

The unescapeEntity change was required so the serializer's numeric references (&#9;, &#10;, &#13;) round-trip. Two things were wrong before this PR: XML.toString() did not escape TAB/LF/CR (the #1092 regression from #1070), and — separately — unescapeEntity rejected those same numeric references as "invalid" even though they are valid XML (#1059).

To fix the serializer I made mustEscape escape all ISO control characters, including #x9/#xA/#xD (literal TAB/LF/CR get whitespace-normalized by conforming parsers, so they can only survive a round trip as &#9;, &#10;, &#13;). I then had to move the parse-time validation off mustEscape onto a dedicated isValidXmlCharacter that implements the XML 1.0 Char production (#x9 | #xA | #xD | [#x20-#xD7FF] | ...).

That gate is exactly what your &#133; example now hits. &#133; is U+0085, which is in [#x20-#xD7FF], so it is a valid XML 1.0 character and is now accepted. Master was over-rejecting it: U+0085 is an ISO control, so the old mustEscape-based check threw. So the new behaviour is arguably more spec-correct — it's just broader than the TAB/LF/CR scope the PR title implies.

Two options, your call:

  1. Keep it as-is and I'll add a line to the PR description plus a comment on isValidXmlCharacter noting that numeric references for valid XML 1.0 C1 controls (e.g. U+0085) are now accepted as a side effect of the parser gate change.
  2. Narrow unescapeEntity to accept only the characters the serializer can emit plus the pre-existing valid range — i.e. re-add the ISO-control exclusion so C1 controls are still rejected on parse.

I lean toward (1) since U+0085 is genuinely valid XML, but I don't want to widen parser acceptance without your sign-off. Which do you prefer?

XML.mustEscape() is shared by XML.escape() (serialization) and
XMLTokener.unescapeEntity() (parsing), but the two callers need opposite
answers for #x9/#xA/#xD. stleary#1070 added those codepoints to the valid-range
clause to fix unescape("&stleary#10;"), which also stopped XML.toString() and
JSONML.toString() from escaping literal TAB, LF and CR. Literal
occurrences of these characters are subject to whitespace normalization
by conforming XML parsers, so a value like "Lettuce\nTomato" loses its
line breaks when the generated XML is read back by any standard parser.
This regressed stleary#1092.

Split the two concerns: mustEscape() returns true for every ISO control
character again (serialization), and the new isValidXmlCharacter() keeps
the previous numeric-reference validation for the parsing path, so &stleary#9;,
&stleary#10; and &stleary#13; are still accepted (stleary#1059/stleary#1070 behaviour unchanged).

isValidXmlCharacter() stays as strict as before for the C1 control
characters (#x7F-#x9F): they fall inside [#x20-#xD7FF] and are legal XML
1.0 characters, but this library has always rejected references to them,
and widening the range here would silently change what XML.toJSONObject
accepts. Only the serialization of TAB/LF/CR changes.

Fixes stleary#1092
@Lyin-OTTF
Lyin-OTTF force-pushed the fix/xml-serialize-escape-whitespace branch from 3b93afd to fea3a2c Compare October 26, 2026 00:35
@Lyin-OTTF

Copy link
Copy Markdown
Author

You are right, that was an unintended behaviour change and &#133; should keep throwing.

The cause: I made isValidXmlCharacter accept the XML 1.0 Char range as written in the spec, and #x7F-#x9F falls inside [#x20-#xD7FF], so the new predicate accepted references the old shared check rejected.

Fixed in fea3a2c. isValidXmlCharacter is now as strict as the previous code for the parsing path: it returns false for every ISO control character except #x9, #xA and #xD, which is exactly what mustEscape used to answer before this PR. The only thing that changed is the serialization path, where TAB/LF/CR are written as &#9;/&#10;/&#13; again.

I added your case as a regression test (testRejectsC1ControlCharacterReference), together with the neighbouring &#127; and &#159;, so the parse result can't drift again. mvn test: 828 tests, 0 failures.

@sonarqubecloud

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JSONML.toString() and XML.toString() omit escaping for literal newlines (\n), causing whitespace loss in downstream XML parsers (Regression from #1070)

2 participants